package com.blogs.meachine;

import com.blogs.enums.TurnstileEvents;
import com.blogs.enums.TurnstileStates;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: xiaokai
 * @Description: 设置模拟存储持久化介质
 * @Date: 2019/5/28
 * @Version: 1.0
 */
@Component
public class BizStateMachinePersist implements StateMachinePersist<TurnstileStates, TurnstileEvents, Integer> {

    static Map<Integer, TurnstileStates> cache = new HashMap<>(100);

    /**
     * 写入当前状态介质
     * @param stateMachineContext
     * @param integer
     * @throws Exception
     */
    @Override
    public void write(StateMachineContext<TurnstileStates, TurnstileEvents> stateMachineContext, Integer integer) throws Exception {
        cache.put(integer, stateMachineContext.getState());

    }

    /**
     * 读取当前状态介质
     * @param integer
     * @return
     * @throws Exception
     */
    @Override
    public StateMachineContext<TurnstileStates, TurnstileEvents> read(Integer integer) throws Exception {

        return cache.containsKey(integer) ?
                new DefaultStateMachineContext<>(cache.get(integer),null,null,null,null,"turnstileStateMachine"):
                new DefaultStateMachineContext<>(TurnstileStates.Locked,null,null,null,null,"turnstileStateMachine");
    }
}
